package com.ttt.adbgui.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

@Slf4j
@Component
public class RunCMD {
    public String run(String cmd, JTextPane textPane) {

        String cmdPath = "C:\\";
        log.info(cmd);
        String result="";
        File dir = new File(cmdPath);

        try {
            Process ps = Runtime.getRuntime().exec(cmd, null, dir);
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
            String line = null;
            while ((line = br.readLine()) != null) {
                addTextPanel(textPane,line);
                result+=line+"\n";
            }
            br.close();
            System.out.println("close ... ");
            ps.waitFor();
            System.out.println("wait over ...");
            return result;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("child thread donn");
        return null;
    }
    
    public void addTextPanel(JTextPane textPane,String text){
        String beforeText = textPane.getText();
        String afterText = beforeText+ "\n" +text;
        textPane.setText(afterText);
    }

    public String runAppend(String cmd, JTextArea textArea) {

        String cmdPath = "C:\\";
        log.info(cmd);
        String result="";
        File dir = new File(cmdPath);

        try {
            Process ps = Runtime.getRuntime().exec(cmd, null, dir);
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                textArea.append(line+"\n");
                result+=line+"\n";
            }
            br.close();
            System.out.println("close ... ");
            ps.waitFor();
            System.out.println("wait over ...");
            return result;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("child thread donn");
        return null;
    }

}
